<!-- 选择用户弹窗, 根据类型查询 -->
<template>
  <div>
    <a-modal
      :maskClosable="false"
      :title="title"
      :bodyStyle="{ paddingTop: '15px' }"
      :destroyOnClose="true"
      centered
      :width="1200"
      v-model="visible"
      @cancel="handleCancel"
      @ok="handleConfirm"
    >
      <a-form layout="inline">
        <a-row>
          <a-col :md="7" :sm="12">
            <a-form-item label="关键字">
              <a-input
                v-model="queryParam.keyword"
                placeholder="姓名/手机号/单位职务/单位名称"
                style="width: 250px"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="12">
            <a-form-item label="用户类型:">
              <a-select
                v-model="queryParam.applyType"
                placeholder="请选择"
                :showArrow="true"
                allowClear
                mode="multiple"
                class="min-width-15"
                :filter-option="filterOption"
              >
                <a-select-option
                  v-for="dict in Dict.getLocal('applyTypeDict')"
                  :key="dict.dictLabel"
                  :value="dict.dictValue"
                >
                  {{ dict.dictLabel }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="12">
            <a-form-item label="会员职务">
              <a-select
                v-model="queryParam.levelIds"
                mode="multiple"
                placeholder="请选择会员职务"
                allowClear
                style="width: 150px"
                :filter-option="filterOption"
              >
                <a-select-option v-for="item in downList.memberLevel" :value="item.id" :key="item.id"
                  >{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="12">
            <a-form-item label="会员状态">
              <a-select
                v-model="queryParam.memberStateIds"
                mode="multiple"
                placeholder="请选择会员状态"
                allowClear
                :filter-option="filterOption"
                style="width: 150px"
              >
                <a-select-option v-for="item in downList.memberStatus" :value="item.id" :key="item.id"
                  >{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="5" :sm="12" v-if="dataSource === DataSourceEnum.MEMBERLIST">
            <a-form-item label="缴费状态">
              <a-select
                v-model="queryParam.paymentStatusIds"
                mode="multiple"
                placeholder="请选择缴费状态"
                allowClear
                class="min-width-15"
                :filter-option="filterOption"
              >
                <a-select-option
                  v-for="dict in Dict.getLocal('paymentStatusDict')"
                  :key="dict.dictValue"
                  :value="dict.dictValue"
                >
                  {{ dict.dictLabel }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="7" :sm="12">
            <a-form-item label="单位身份">
              <a-select
                v-model="queryParam.initRoleIds"
                mode="multiple"
                placeholder="请选择单位身份"
                allowClear
                :filter-option="filterOption"
                class="min-width-15"
              >
                <a-select-option
                  v-for="dict in Dict.getLocal('companyIdentityDict')"
                  :key="dict.dictValue"
                  :value="dict.dictValue"
                  >{{ dict.dictLabel }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <template v-if="dataSource === DataSourceEnum.USERLIST">
            <a-col :md="5" :sm="12">
              <a-form-item label="小程序">
                <a-select
                  v-model="queryParam.isLogin"
                  placeholder="请选择"
                  mode="multiple"
                  allowClear
                  :showArrow="true"
                  style="width: 150px"
                  :filter-option="filterOption"
                >
                  <a-select-option
                    v-for="dict in Dict.getLocal('isLoginDict')"
                    :key="dict.dictValue"
                    :value="dict.dictValue"
                  >
                    {{ dict.dictLabel }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="12">
              <a-form-item label="公众号">
                <a-select
                  v-model="queryParam.isOfficialAccount"
                  placeholder="请选择"
                  mode="multiple"
                  allowClear
                  :showArrow="true"
                  style="width: 150px"
                  :filter-option="filterOption"
                >
                  <a-select-option
                    v-for="dict in Dict.getLocal('isOfficialAccountDict')"
                    :key="dict.dictValue"
                    :value="dict.dictValue"
                  >
                    {{ dict.dictLabel }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>

          <a-col :md="6" :sm="12">
            <a-form-item label="用户标签">
              <a-select
                placeholder="请选择标签"
                v-model="queryParam.groupIds"
                allowClear
                :showArrow="true"
                mode="multiple"
                class="min-width-18"
                :filter-option="filterOption"
              >
                <a-select-option v-for="(item, idx) in labelLists" :key="idx" :value="item.id" :label="item.name">
                  <span role="img" :aria-label="item.name"></span>
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- <a-col :md="19" :sm="12">
            <a-form-item label="行业">
              <SelectIndustry v-model="queryParam.industryIds" :treeData="downList.industry"></SelectIndustry>
            </a-form-item>
          </a-col> -->
          <a-col :md="3" :sm="12">
            <a-button class="_mt-5" type="primary" @click="handleSearch(true)">查询</a-button>
            <a-button class="_mt-5" style="margin-left: 8px" @click="handleReset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
      <div class="_pb-10 _pt-10 disFlxAC">
        <span class="_pr-10 color9"
          >已勾选<span class="colorZS _pl-2 _pr-2 fw-7">{{ selectedRowKeys.length }}</span
          >位人员</span
        >
        <a-button v-if="total" type="primary" ghost @click="checkedAllMemberList"
          >{{ isAllChecked ? '取消勾选' : '勾选' }}"筛选条件"下全部<span class="fw-7 _pl-2 _pr-2">{{ total }}</span
          >位人员</a-button
        >
      </div>
      <a-card :bordered="false" :bodyStyle="{ padding: '0px' }">
        <s-table
          size="default"
          ref="table"
          rowKey="userId"
          :columns="columns"
          :data="loadData"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            getCheckboxProps: record => ({
              props: {
                ...record,
                disabled: defaultSelectedKeys.includes(record.userId) || record.disabled
              }
            })
          }"
        >
          <!-- 用户信息 -->
          <template slot="userInfo" slot-scope="text, record">
            <div class="disFlxAC">
              <a-avatar size="default" icon="user" :src="record.avatar" />
              <div class="_pl-10 fz-12">
                <div>{{ record.userName }}</div>
                <div>{{ record.phone }}</div>
              </div>
            </div>
          </template>
          <!-- 用户类型 -->
          <template slot="applyType" slot-scope="text, record">
            <DictTag :options="Dict.getLocal('applyTypeDict')" :value="record.applyType" isText showBorder />
          </template>
          <!-- 公众号关注状态 -->
          <span slot="isOfficialAccount" slot-scope="text">
            <DictTag :options="Dict.getLocal('isOfficialAccountDict')" :value="text" isText />
          </span>
        </s-table>
      </a-card>
    </a-modal>
  </div>
</template>

<script>
import { MemberInfoSearchVoList, memberLevelGetDownList, AllMemberInfoStatisticsVo } from '@/api/system/system'
import { memberTypeList } from '@/api/member/member'
import { STable } from '@/components'
import { DataSourceEnum } from '@/enums/member'
import DictTag from '@/components/DictTag'
import { getTagUserList } from '@/api/member/grouping'
import { cloneDeep, uniq } from 'lodash-es'
import SelectIndustry from '@/components/SelectIndustry/index.vue'

export default {
  props: ['dataSource', 'objectId'],
  components: {
    STable,
    DictTag,
    SelectIndustry
  },
  data() {
    return {
      visible: false,
      queryParam: {
        levelIds: [],
        memberStateIds: [],
        paymentStatusIds: [],
        industryIds: [],
        groupIds: [],
        initRoleIds: [],
        keyword: undefined,
        applyType: undefined,
        isLogin: undefined,
        isOfficialAccount: undefined
      },
      columns: [
        {
          title: '用户信息',
          dataIndex: 'userInfo',
          width: '200px',
          scopedSlots: { customRender: 'userInfo' },
          align: 'left'
        },
        { title: '用户单位', dataIndex: 'companyName', ellipsis: true },
        { title: '单位职务', dataIndex: 'companyPosition', width: '120px', ellipsis: true },
        {
          title: '用户类型',
          dataIndex: 'applyType',
          width: '90px',
          scopedSlots: { customRender: 'applyType' }
        },
        { title: '会员职务', dataIndex: 'memberLevelName', width: '100px', ellipsis: true },
        {
          title: '公众号',
          dataIndex: 'isOfficialAccount',
          width: '120px',
          scopedSlots: { customRender: 'isOfficialAccount' }
        }
      ],
      loadData: async parameter => {
        let page = {
          size: parameter.pageSize,
          current: parameter.current
        }
        this.pagination.current = parameter.current
        let res = MemberInfoSearchVoList(
          Object.assign(page, this.queryParam, { dataSource: this.dataSource, objectId: this.objectId })
        )
        res.then(r => {
          this.total = r.data.total
          r.data.records.forEach(v => {
            this.$set(v, 'disabled', this.isAllChecked && this.defaultSelectedKeys.includes(v.userId))
          })
          return r
        })
        return res
      },
      pagination: {
        current: 1,
        pageSize: 10
      },
      selectedRowKeys: [],
      defaultSelectedKeys: [],

      downList: {
        memberLevel: [],
        memberStatus: [
          { id: 1, name: '正常' },
          { id: 0, name: '退会' }
        ],
        industry: [],
        label: []
      },
      labelLists: [],
      total: 0,
      isAllChecked: false,
      DataSourceEnum
    }
  },
  computed: {
    title() {
      if (this.dataSource === DataSourceEnum.MEMBERLIST) {
        return '会员列表'
      } else if (this.dataSource === DataSourceEnum.REGISTERLIST) {
        return '活动报名列表'
      } else {
        return '用户列表'
      }
    }
  },
  methods: {
    filterOption(input, option) {
      const children = option.componentOptions.children.find(item => item.text)
      if (children) {
        return children.text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      }
      return false
    },

    moduleShow(selectedIds) {
      this.resetQueryParam()
      this.getMemberLevelGetDownList()
      this.getMemberTypeList()
      this.getLabelList()

      this.defaultSelectedKeys = cloneDeep(selectedIds) || []
      this.selectedRowKeys = cloneDeep(selectedIds) || []

      this.isAllChecked = false
      this.visible = true
    },
    resetQueryParam() {
      Object.keys(this.queryParam).forEach(k => {
        if (k === 'keyword') this.queryParam[k] = undefined
        else this.queryParam[k] = []
      })
    },
    // 会员职务下拉
    async getMemberLevelGetDownList() {
      let res = await memberLevelGetDownList()
      this.downList.memberLevel = res.data || []
    },
    //行业下拉
    async getMemberTypeList() {
      let res = await memberTypeList('industryId')
      this.downList.industry = res.data.industryId || []
    },
    getLabelList() {
      getTagUserList({ type: 0 }).then(res => {
        this.labelLists = res.data
      })
    },
    handleSearch(resetAllChecked) {
      if (resetAllChecked) {
        this.isAllChecked = false
      }
      this.$refs.table.refresh(true)
    },
    //表格数据选中
    onSelectChange(selectedRowKeys, selectedRows) {
      // console.log(selectedRowKeys, selectedRows)
      this.selectedRowKeys = uniq([...this.defaultSelectedKeys, ...selectedRowKeys])
    },
    handleReset() {
      Object.keys(this.queryParam).forEach(k => {
        if (k != 'keyword') this.queryParam[k] = []
        else this.queryParam[k] = undefined
      })
      this.isAllChecked = false
      this.$refs.table.refresh(true)
    },
    handleCancel() {
      this.visible = false
    },
    handleConfirm() {
      this.visible = false
      this.$emit('confirmUser', this.selectedRowKeys)
    },

    async checkedAllMemberList() {
      this.isAllChecked = !this.isAllChecked
      if (this.isAllChecked) {
        let res = await AllMemberInfoStatisticsVo({
          ...this.queryParam,
          dataSource: this.dataSource,
          objectId: this.objectId
        })

        this.selectedRowKeys = uniq([...this.defaultSelectedKeys, ...res.data.smsUserIds])
      } else {
        this.selectedRowKeys = [...this.defaultSelectedKeys]
      }
      this.handleSearch() // 刷新表格禁用条件
    }
  }
}
</script>
<style scoped>
.btn {
  text-align: right;
}
</style>
